package com.example.whereismystuff.views;

import java.util.ArrayList;
import java.util.Calendar;

import com.example.whereismystuff.R;
import com.example.whereismystuff.classes.Item;
import com.example.whereismystuff.classes.ItemDataBaseAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

/**
 * This view displays all items initially but also allows the user to search by several different methods.
 * @author NullPointers
 *
 */
public class SearchView extends ListActivity {
	String username;
	private ListView listView;

	ItemDataBaseAdapter mySQLiteAdapter;
	private int mYear;
	private int mMonth;
	private int mDay;
	static final int DATE_DIALOG_ID = 1;
	ArrayList<Item> currentItemList;
	String[] items;
	String s_Date;
	String tmpYear;

	private final String SLASH = "/";
	private final String EMPTY = "";

	ArrayList<String> tagsArray;

	AlertDialog.Builder tagDialog;
	String search, zipCode;
	Cursor currentItems;
	ArrayList<String> itemnames;

	/**
	 * Method used to Instantiate Object and set the Layout for the Activity
	 * @param Bundle
	 */
	/**
	 * onCreate sets up everything in the beggining of staring the activity. It essentially shows all
	 * of the items from the database
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mySQLiteAdapter = new ItemDataBaseAdapter(this);

		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();
		Cursor cursor = mySQLiteAdapter.queueAll();
		startManagingCursor(cursor);
		NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
		Bundle extras = getIntent().getExtras();
		// listContent.setAdapter(cursorAdapter);
		setListAdapter(cursorAdapter);
		//mySQLiteAdapter.close();
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		tmpYear = EMPTY + mYear;
		s_Date = mMonth + SLASH + mDay + SLASH + tmpYear.substring(2,4);
		tagDialog = new AlertDialog.Builder(this);
		tagsArray = new ArrayList<String>();
		username = getIntent().getExtras().getString("Username");
		search = EMPTY;
		zipCode = EMPTY;
		itemnames = mySQLiteAdapter.queueAllItems();
		currentItems = mySQLiteAdapter.queueAll();
	}

	/**
	 * Creates the menu
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(this).inflate(R.menu.search_menu, menu);
		return (super.onCreateOptionsMenu(menu));
	}

	/**
	 * Tells which method to cal based on the pressed menu item
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.searchByName:
			SearchByName();
			return true;
		case R.id.searchFound:
			SearchFound();
			return true;
		case R.id.searchLost:
			SearchLost();
			return true;
		case R.id.searchByTag:
			SearchByTag();
			return true;
		case R.id.searchByDate:
			SearchByDate();
			return true;
		case R.id.searchByLocation:
			SearchByZipCode();
		case R.id.searchByMatch:
			SearchByMatch();
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Redirects the user to viewAnItem which shows all of the information of the item 
	 */
	@Override
	protected void onListItemClick(ListView list, View view, int position,
			long id) {
		super.onListItemClick(list, view, position, id);
		try
		{
			Class c = Class.forName("com.example.whereismystuff.views.ViewAnItem");
			Intent intent = new Intent(this, c);
			String itemName = itemnames.get(position);
			currentItems.moveToPosition(position);
			mySQLiteAdapter.open();
			//String found = mySQLiteAdapter.getSingleEntryFound(itemName);
			String found = currentItems.getString(currentItems.getColumnIndex("FOUND"));
			String description = currentItems.getString(currentItems.getColumnIndex("DESCRIPTION"));
			String id2 = currentItems.getString(currentItems.getColumnIndex("_id"));
			String image = currentItems.getString(currentItems.getColumnIndex("IMAGE"));
			//mySQLiteAdapter.close();
			//String zipCode = mySQLiteAdapter.getSingleEntryZipCode(itemName);
			String zipCode = currentItems.getString(currentItems.getColumnIndex("ZIPCODE"));
			ArrayList<String> tags = new ArrayList<String>();// = mySQLiteAdapter.getSingleEntryTags(itemName);
			tags.add(currentItems.getString(currentItems.getColumnIndex("BOOK")));
			tags.add(currentItems.getString(currentItems.getColumnIndex("ELECTRONIC")));
			tags.add(currentItems.getString(currentItems.getColumnIndex("PERSONAL")));
			ArrayList<String> temp =  new ArrayList<String>();
			temp.add(itemName);
			temp.add(found);
			Bundle dataBundle = new Bundle();
			dataBundle.putString("id", id2);
			dataBundle.putString("Username", username);
			dataBundle.putString("ItemName", itemName);
			dataBundle.putString("Description", description);
			dataBundle.putString("Found", found);
			dataBundle.putString("ZipCode", zipCode);
			dataBundle.putString("Image", image);
			if(tags != null){
				dataBundle.putString("Book", tags.get(0));
				dataBundle.putString("Electronic", tags.get(1));
				dataBundle.putString("Personal", tags.get(2));
			}
			else{
				dataBundle.putString("Book", null);
				dataBundle.putString("Electronic", null);
				dataBundle.putString("Personal", null);
			}
			intent.putExtras(dataBundle);
			startActivity(intent);
		}
		catch(ClassNotFoundException e)
		{
			e.printStackTrace();
		}
	}
	/**
	 * SearchbyName quereys the database by the string inputed by the user
	 */
	private void SearchByName(){
		final Dialog dialog = new Dialog(SearchView.this);

		dialog.setContentView(R.layout.search_by_name);
		dialog.setTitle("Search By Name");

		// get the Refferences of views
		final  EditText text =(EditText)dialog.findViewById(R.id.searchNameInput);
		final Button okButton = (Button)dialog.findViewById(R.id.okButton);
		okButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setSearchValue(text.getText().toString());
				Toast.makeText(getApplicationContext(), search, Toast.LENGTH_LONG).show();
				SearchbyNameHelper();
				dialog.dismiss();

			}
		});

		dialog.setCancelable(true);

		dialog.show();
	}

	/**
	 * Finds all matches within the database based on location and name
	 */
	private void SearchByMatch() {
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();
		//Cursor cursor1 = mySQLiteAdapter.queueAllFiltered("NA", "FOUND", null);
		//Cursor cursor2 = mySQLiteAdapter.queueAllFiltered("NA", "LOST", null);
		Cursor cursor = mySQLiteAdapter.queueMatches();
		startManagingCursor(cursor);
		NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
		setListAdapter(cursorAdapter);
		// mySQLiteAdapter.close();
	}

	/**
	 * Helper method for search by name
	 */
	private void SearchbyNameHelper(){
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();

		Cursor cursor = mySQLiteAdapter.queueAllSearchQuery(search);
		if(cursor!=null){
			startManagingCursor(cursor);
			NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
			setListAdapter(cursorAdapter);
		}
	}

	/**
	 * Allows the user to search items based on zipcodes
	 */
	private void SearchByZipCode(){
		final Dialog dialog = new Dialog(SearchView.this);

		dialog.setContentView(R.layout.search_by_zipcode);
		dialog.setTitle("Search By Zip Code");

		// get the Refferences of views
		final  EditText text =(EditText)dialog.findViewById(R.id.searchByZipCodeInput);
		final Button okButton = (Button)dialog.findViewById(R.id.okButtonZ);
		okButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				setZipCode(text.getText().toString());
				SearchbyLocationHelper();
				dialog.dismiss();
			}
		});

		dialog.setCancelable(true);

		dialog.show();
	}

	/**
	 * Helper method for search by location
	 */
	private void SearchbyLocationHelper(){
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();

		Cursor cursor = mySQLiteAdapter.queueAllLocationQuery(zipCode);
		if(cursor!=null){
			startManagingCursor(cursor);
			NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
			setListAdapter(cursorAdapter);
		}

	}

	/**
	 * Sets the string for the search
	 * @param s
	 */
	private void setSearchValue(String s){
		search = s;
	}

	/**
	 * sets the zipcode for the search
	 * @param s
	 */
	private void setZipCode(String s){
		zipCode = s;
	}
	/**
	 * Displays all found items
	 */
	private void SearchFound() {
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();

		Cursor cursor = mySQLiteAdapter.queueAllFiltered("NA", "FOUND", null);
		startManagingCursor(cursor);
		NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
		setListAdapter(cursorAdapter);
		//mySQLiteAdapter.close();
	}

	/**
	 * displays all lost items
	 */
	private void SearchLost() {
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();

		Cursor cursor = mySQLiteAdapter.queueAllFiltered("NA", "LOST", null);
		startManagingCursor(cursor);
		NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
		setListAdapter(cursorAdapter);
		//mySQLiteAdapter.close();
	}

	/**
	 * allows the user to search by different tags
	 */
	private void SearchByTag() {
		final Dialog dialog = new Dialog(SearchView.this);

		dialog.setContentView(R.layout.search_by_tag);
		dialog.setTitle("Search By Tag");

		// get the References of views
		final  CheckBox book = (CheckBox) dialog.findViewById(R.id.c_isBook);
		final  CheckBox electronic = (CheckBox) dialog.findViewById(R.id.c_isElectronic);
		final  CheckBox personal = (CheckBox) dialog.findViewById(R.id.c_isPersonal);
		final Button okButton = (Button)dialog.findViewById(R.id.okButtonT);
		okButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if(tagsArray.isEmpty()){
					tagsArray.add(EMPTY + book.isChecked());
					tagsArray.add(EMPTY + electronic.isChecked());
					tagsArray.add(EMPTY + personal.isChecked());
				} else {
					tagsArray.set(0, EMPTY + book.isChecked());
					tagsArray.set(1, EMPTY + electronic.isChecked());
					tagsArray.set(2, EMPTY + personal.isChecked());
				}

				SearchBytagHelper(tagsArray);
				dialog.dismiss();
			}
		});

		dialog.setCancelable(true);

		dialog.show();
	}

	/**
	 * helper method for search by tags
	 * @param arr
	 */
	private void SearchBytagHelper(ArrayList<String> arr){
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();

		Cursor cursor = mySQLiteAdapter.queueAllFiltered("NA", "NA", arr);
		startManagingCursor(cursor);
		NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
		setListAdapter(cursorAdapter);
	}

	/**
	 * Bring up a date dialog to find the item by date
	 */
	private void SearchByDate() {
		showDialog(DATE_DIALOG_ID);


	}

	/**
	 * Helper method for search by date
	 */
	private void SearchByDateHelper(){
		mySQLiteAdapter = new ItemDataBaseAdapter(this);
		mySQLiteAdapter.open();

		Cursor cursor = mySQLiteAdapter.queueAllFiltered(s_Date, "NA", null);
		startManagingCursor(cursor);
		NewListAdapter cursorAdapter = new NewListAdapter(this, cursor);
		setListAdapter(cursorAdapter);
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {

		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear + 1;
			mDay = dayOfMonth;


			tmpYear = EMPTY + mYear;
			s_Date = mMonth + SLASH + mDay + SLASH + tmpYear.substring(2,4);
			SearchByDateHelper();

		}
	};

	protected void onResume() {
		super.onResume();
	}
	/**
	 * sends the suer back to the dashboard when back is pressed
	 */
	public void onBackPressed() {
		try{
			Class c = Class.forName("com.example.whereismystuff.views.DashboardView");
			Intent i = getIntent();
			Bundle extras = i.getExtras();
			extras.putString("calling-activity", "all-items");
			//i.putExtra("calling-activity", "myitems");
			i = new Intent(getApplicationContext(), c);
			i.putExtras(extras);
			startActivity(i);
			finish();
		} catch (ClassNotFoundException e){
			e.printStackTrace();
		}
	}
}
